<script setup lang="ts">
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus';
import { nextTick, ref} from 'vue';
import { ApiUser } from '../../api';

const model=ref<API.User.Add>({
    user_name:'',
    user_pwd:'',
})
// const valid=ref<API.User.ValidName>({
//     user_name:''
// })
const canael=async()=>{
  await  ElMessageBox.confirm('取消数据会丢失哦？', '提示', {type: 'warning'})
    show.value=false
}
const show=ref<boolean>(false)
const formRef=ref<FormInstance|null>(null)
const emits=defineEmits<{(name:'save',model:API.User.Add):void}>()
const roules:FormRules={
    user_name:[
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 10, message: '长度在 2 到 10个字符', trigger: 'blur' },
       //@ts-ignore
        {validator:async(rule, value, callback)=>{
            // const data=await ApiUser.valid(valid.value)\
            if(1=== await ApiUser.valid({user_name:value})){
                callback(new Error('用户名已存在'))
            }else{
                callback()
            }
            },trigger:'blur'
           
        }
    ]
}
defineExpose({
    begin:()=>{
        formRef.value?.resetFields()
        nextTick(()=> show.value=true)
    }
})
const save=async()=>{
    await formRef?.value?.validate()
    await ApiUser.add(model.value)
    emits('save',model.value)
    show.value=false
    ElMessage.success('添加成功')
}
</script>

<template>
  <el-dialog title="添加角色"  width="300px" v-model="show">
      <el-form ref="formRef" :model="model" label-width="80px" :rules="roules">
          <el-form-item label="用户名称" prop="user_name">
            <el-input v-model="model.user_name" placeholder="请输入用户名" ></el-input>
          </el-form-item>
      </el-form>
      <div slot="footer">
          <el-button @click="canael">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
      </div>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>